package cn.tedu.mvccoolshark.controller;

import cn.tedu.mvccoolshark.mapper.ProductMapper;
import cn.tedu.mvccoolshark.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ProductController {
    /**
     * 自动装配映射
     */
    @Autowired
    private ProductMapper productMapper;

    /**
     * 添加商品
     * @param product
     * @return
     */
    @RequestMapping("/v1/product/insert")
    @ResponseBody
    public String insertProduct(Product product){
        productMapper.insert(product);
        return "保存成功";
    }

    /**
     * 修改商品
     * @param product
     * @return
     */
    @RequestMapping("/v1/product/update")
    @ResponseBody
    public String updateProduct(Product product){
        productMapper.update(product);
        return "修改成功";
    }
    /**
     * 商品列表
     */
    @RequestMapping("/v1/product/select")
    @ResponseBody
    public String selectProduct(){
        List<Product> list = productMapper.selectAll();
// 1.定义html字符串
        String html = "<table border='1'>";
        html += "<caption>商品列表</caption>";
        html += "<tr><th>id</th><th>标题</th><th>价格</th><th>库存</th><th>" +
                "操作 </th></tr>";
// 2.使用foreach遍历每个商品对象，并将其添加到html标签中
        for (Product p: list) {
            html += "<tr>";
            html += "<td>" + p.getId() + "</td>";
            html += "<td>" + p.getTitle() + "</td>";
            html += "<td>" + p.getPrice() + "</td>";
            html += "<td>" + p.getNum() + "</td>";
        // http://localhost:8080/delete?id=xxx
            html += "<td><a href='/v1/product/delete?id=" + p.getId() + "'>" +
                    "删除 </a>" + "</td>";
            html += "</tr>";
        }
        html += "</table>";
        html +="<a href='/index.html'>商品管理系统(MyBatis版)</a> <br>";
        html +="<a href='/insert.htm>添加商品</a>";
        return html;
    }
    @RequestMapping("/v1/product/delete")
    @ResponseBody
    public String deleteProduct(Product id){
        productMapper.delete(id);
        return "删除成功";
    }
}
